<template>
	<view class="bi-analysis-container">
		<view class="header">
			<text class="title">BI 分析</text>
		</view>
		
		<!-- 总览卡片 - 移到最上方 -->
		<view class="overview-card">
			<view class="total-stats">
				<view class="stat-item">
					<text class="label">总学习时长</text>
					<text class="value">{{ totalDuration }}</text>
				</view>
				<view class="stat-item">
					<text class="label">学习课程数</text>
					<text class="value">{{ watchStats.length }}</text>
				</view>
			</view>
		</view>
		
		<!-- 课程学习列表 -->
		<view class="course-list">
			<view class="list-title">学习记录</view>
			<view 
				class="course-item" 
				v-for="(item, index) in watchStats" 
				:key="index"
				@tap="goToCourseDetail(item.courseId)"
			>
				<view class="course-info">
					<text class="course-name">{{ item.courseName }}</text>
					<view class="stats-info">
						<text class="watch-count">观看 {{ item.watchCount }} 次</text>
						<text class="duration">{{ item.formattedDuration }}</text>
					</view>
				</view>
				<text class="arrow">›</text>
			</view>
		</view>

		<!-- 无数据提示 -->
		<view class="empty-tip" v-if="watchStats.length === 0">
			<image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
			<text>暂无学习记录</text>
		</view>	

		<!-- 添加智能分析表单 -->
		<view class="analysis-form">
			<text class="section-title">智能分析</text>
			<view class="form-item">
				<text class="required">*</text>
				<text class="label">分析目标</text>
				<input
					v-model="formData.goal" 
					class="textarea" 
					placeholder="分析该同学的成绩"
				/>
			</view>
			<view class="form-item">
				<text class="label">图表名称</text>
				<input 
					v-model="formData.name" 
					class="input" 
					placeholder="成绩分析"
				/>
			</view>
			<view class="form-item">
				<text class="label">图表类型</text>
				<picker 
					@change="handleTypeChange" 
					:value="typeIndex" 
					:range="chartTypes"
					class="picker"
				>
					<view class="picker-text">{{ chartTypes[typeIndex] }}</view>
				</picker>
			</view>
			<view class="form-item">
				<text class="label">原始数据</text>
				<view class="upload-area">
					<button class="upload-btn" @tap="chooseFile">上传 CSV/XLSX 文件</button>
					<text class="file-name" v-if="formData.file">{{ formData.file.name }}</text>
				</view>
			</view>
			<view class="form-actions">
				<button 
					class="submit-btn" 
					@tap="handleSubmit" 
					:disabled="!canSubmit || loading"
					:loading="loading"
				>
					{{ loading ? '分析中...' : '提交分析' }}
				</button>
				<button class="reset-btn" @tap="handleReset">重置</button>
			</view>
		</view>

		<view class="chart-section" v-if="aiChartData">
			<text class="section-title">智能BI分析</text>
			<view class="chart-container">
				<qiun-data-charts 
					:type="aiChartData.series[0].type"
					:opts="opts"
					:chartData="transformChartData(aiChartData)"
					:canvas2d="true"
					canvasId="ai-charts"
				/>
			</view>
		</view>

		<!-- 学习记录列表 -->
		<view class="learning-records" v-if="analysisResult">
			<text class="section-title">学习建议</text>
			<view class="analysis-result">{{ analysisResult }}</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { courseApi } from '@/utils/api'

// 转换函数：将 echarts 数据格式转换为 uCharts 所需格式
const transformChartData = (echartsData) => {
	return {
		categories: echartsData.xAxis.data,
		series: echartsData.series
	}
}

// 图表配置
const opts = {
	type: 'line',
	canvasId: 'charts',
	canvas2d: true,
	background: '#FFFFFF',
	animation: true,
	timing: 'easeOut',
	duration: 1000,
	padding: [15, 15, 10, 15],
	legend: {
		show: true
	},
	xAxis: {
		disableGrid: true,
		axisLine: true,
		axisLineColor: '#CCCCCC',
		title: '科目'
	},
	yAxis: {
		gridType: 'dash',
		dashLength: 2,
		data: [{
			min: 0,
			max: 100,
			title: '分数'
		}]
	},
	extra: {
		line: {
			type: 'straight',
			width: 2,
			activeType: 'hollow'
		}
	}
}


// 表单数据
const formData = ref({
	goal: '',
	name: '',
	chartType: 'line',
	file: null
})

// 图表类型选择
const chartTypes = ['折线图', '柱状图', '饼图','雷达图','散点图']
const typeIndex = ref(0)
const handleTypeChange = (e) => {
	typeIndex.value = e.detail.value
	const types = ['line', 'bar', 'pie']
	formData.value.chartType = types[typeIndex.value]
}

// 选择文件
const chooseFile = async () => {
	try {
		const res = await uni.chooseFile({
			count: 1,
			extension: ['.xlsx', '.csv']
		})
		formData.value.file = res.tempFiles[0]
	} catch (error) {
		console.error('选择文件失败:', error)
	}
}

// 是否可以提交
const canSubmit = computed(() => {
	return formData.value.goal && formData.value.file
})

// 添加AI分析结果数据
const aiChartData = ref(null)
const analysisResult = ref('')

// 添加loading状态
const loading = ref(false)

// 修改提函数
const handleSubmit = async () => {
	if (!canSubmit.value || loading.value) return
	
	loading.value = true // 开始加载
	
	try {
		const data = new FormData()
		data.append('file', formData.value.file)
		
		const res = await uni.uploadFile({
			url: '/api/chart/gen',
			filePath: formData.value.file.path,
			name: 'file',
			formData: {
				goal: formData.value.goal,
				name: formData.value.name,
				chartType: formData.value.chartType
			}
		})
		
		if (res.statusCode === 200) {
			const result = JSON.parse(res.data)
			if (result.code === 0) {
				aiChartData.value = JSON.parse(result.data.genchart)
				analysisResult.value = result.data.genresult
				
				uni.showToast({
					title: '分析成功',
					icon: 'success'
				})
				handleReset()
			} else {
				throw new Error(result.message || '分析失败')
			}
		}
	} catch (error) {
		console.error('提交失败:', error)
		uni.showToast({
			title: error.message || '分析失败',
			icon: 'error'
		})
	} finally {
		loading.value = false // 结束加载
	}
}

// 重置表单
const handleReset = () => {
	formData.value = {
		goal: '',
		name: '',
		
		chartType: 'line',
		file: null
	}
	typeIndex.value = 0
}

const watchStats = ref([])
const totalDuration = ref('0分钟')

// 添加新的响应式数据
const watchChartData = ref({
	categories: [],
	series: []
})

// 添加图表配置
const watchChartOpts = {
	color: ['#007AFF'],
	padding: [15, 15, 10, 15],
	enableScroll: true,
	legend: {
		show: false
	},
	xAxis: {
		disableGrid: true,
		rotateLabel: true,
		axisLine: true,
		axisLineColor: '#CCCCCC',
		title: '课程名称'
	},
	yAxis: {
		gridType: 'dash',
		dashLength: 2,
		data: [{
			title: '学习时长(分钟)',
			min: 0
		}]
	},
	extra: {
		column: {
			width: 30,
			activeBgColor: '#000000',
			activeBgOpacity: 0.08
		}
	}
}

// 获取观看统计数据
const loadWatchStats = async () => {
	try {
		const res = await courseApi.getWatchStats()
		if (res.code === 0 && res.data) {
			watchStats.value = res.data.map(item => ({
				...item,
				totalDuration: parseInt(item.totalDuration),
				formattedDuration: item.formattedDuration
			}))
			
			// 计算总时长（使用秒数）
			const totalSeconds = watchStats.value.reduce((sum, item) => {
				return sum + parseInt(item.totalDuration || 0)
			}, 0)
			
			// 格式化总时长
			totalDuration.value = formatDurationFromSeconds(totalSeconds)
			
			// 处理图表数据 - 转换为分钟显示
			watchChartData.value = {
				categories: watchStats.value.map(item => item.courseName),
				series: [{
					name: '学习时长',
					// 将秒转换为分钟，四舍五入到1位小数
					data: watchStats.value.map(item => 
						Math.round((parseInt(item.totalDuration || 0) / 60) * 10) / 10
					)
				}]
			}
		}
	} catch (error) {
		console.error('获取观看统计失败:', error)
		uni.showToast({
			title: '获取数据失败',
			icon: 'none'
		})
	}
}

// 新增格式化总时长的函数
const formatDurationFromSeconds = (totalSeconds) => {
	if (!totalSeconds || totalSeconds <= 0) return '0分钟'
	
	const hours = Math.floor(totalSeconds / 3600)
	const minutes = Math.floor((totalSeconds % 3600) / 60)
	const seconds = totalSeconds % 60
	
	if (hours > 0) {
		return `${hours}小时${minutes > 0 ? minutes + '分钟' : ''}`
	} else if (minutes > 0) {
		return `${minutes}分钟${seconds > 0 ? seconds + '秒' : ''}`
	} else {
		return `${seconds}秒`
	}
}

// 跳转到课程详情
const goToCourseDetail = (courseId) => {
	uni.navigateTo({
		url: `/pages/course/detail?id=${courseId}`
	})
}

onMounted(() => {
	loadWatchStats()
})
</script>

<style scoped>
.bi-analysis-container {
	padding: 30rpx;
	background-color: #f6f7f9;
	min-height: 100vh;
}

.header {
	margin-bottom: 30rpx;
}

.title {
	font-size: 42rpx;
	font-weight: bold;
	color: #333;
}

.stats-card {
	background-color: #fff;
	border-radius: 16rpx;
	display: flex;
	justify-content: space-between;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.stats-item {
	text-align: center;
	flex: 1;
}

.stats-item .label {
	display: block;
	color: #666;
	font-size: 24rpx;
	margin-bottom: 10rpx;
}

.value {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	color: #007aff;
}

.chart-section, .learning-records {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
	display: block;
}

.chart-container {
	height: 400rpx;
	width: 100%;
	background-color: #FFFFFF;
}

.record-item {
	display: flex;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 2rpx solid #f5f5f5;
}

.record-item:last-child {
	border-bottom: none;
}

.course-name {
	font-size: 28rpx;
	color: #333;
}

.record-detail {
	font-size: 24rpx;
	color: #666;
}

.analysis-form {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
}

.form-item {
	margin-bottom: 30rpx;
}

.required {
	color: #ff4d4f;
	margin-right: 4rpx;
}

.label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.form-item .label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.form-item .input {
	width: 100%;
	height: 80rpx;
	background-color: #f5f7fa;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	box-sizing: border-box;
}

.textarea {
	height: 160rpx;
	width: 100%;
	background-color: #f5f7fa;
	border-radius: 12rpx;
}

.picker {
	background-color: #f5f7fa;
	border-radius: 12rpx;
	padding: 20rpx;
}

.picker-text {
	font-size: 28rpx;
	color: #333;
}

.upload-area {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.upload-btn {
	background: #f5f7fa;
	color: #333;
	font-size: 28rpx;
	padding: 20rpx 40rpx;
	border-radius: 12rpx;
}

.file-name {
	font-size: 24rpx;
	color: #666;
}

.form-actions {
	display: flex;
	gap: 20rpx;
	margin-top: 40rpx;
}

.submit-btn, .reset-btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
	border-radius: 12rpx;
}

.submit-btn {
	background: #007aff;
	color: #fff;
}

.submit-btn[disabled] {
	opacity: 0.6;
	background: #007aff !important; /* 保持主色调 */
}

/* 加载中状态的样式 */
.submit-btn[loading] {
	opacity: 0.8;
}

.reset-btn {
	background: #f5f7fa;
	color: #666;
}

/* 添加分结果样式 */
.analysis-result {
	font-size: 28rpx;
	color: #333;
	line-height: 1.6;
	padding: 20rpx;
	background-color: #f8f9fa;
	border-radius: 12rpx;
	margin-top: 20rpx;
}

.stats-container {
	min-height: 100vh;
	padding: 30rpx;
	background-color: #f6f7f9;
}

.overview-card {
	background: linear-gradient(135deg, #007aff 0%, #0056b3 100%);
	border-radius: 24rpx;
	padding: 40rpx 30rpx;
	margin-bottom: 30rpx;
	color: #fff;
	box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.2);
}

.total-stats {
	display: flex;
	justify-content: space-around;
}

.stat-item {
	text-align: center;
}

.stat-item .label {
	font-size: 24rpx;
	opacity: 0.8;
	display: block;
	margin-bottom: 10rpx;
}

.stat-item .value {
	font-size: 36rpx;
	font-weight: bold;
	color: #fff;
}

.course-list {
	background: #fff;
	border-radius: 24rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	margin-bottom: 30rpx;
}

.list-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 30rpx;
	color: #333;
}

.course-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 2rpx solid #f5f5f5;
}

.course-item:last-child {
	border-bottom: none;
}

.course-info {
	flex: 1;
}

.course-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
	display: block;
}

.stats-info {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.watch-count,
.duration {
	font-size: 24rpx;
	color: #666;
}

.arrow {
	font-size: 36rpx;
	color: #999;
	font-family: serif;
}

.empty-tip {
	margin-top: 100rpx;
	text-align: center;
	color: #999;
	font-size: 28rpx;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 20rpx;
}

.chart-section {
	background: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.chart-container {
	height: 600rpx;
	width: 100%;
}
</style> 